<template>
  <div class="container">
    <el-dialog :title="showTitle" :visible="showAddDialog" @close="btnCancel" >
      <el-form :model="formData" ref="addForm" :rules="rules" label-width="100px">
        <el-form-item label="文章标题:" prop="title">
          <el-input v-model="formData.title"></el-input>
        </el-form-item>
        <el-form-item label="文章内容:" prop="articleBody">
          <quill-editor
            :content="formData.articleBody"
            @change="onEditorChange($event)"
          ></quill-editor>
        </el-form-item>
        <el-form-item label="视频地址:" prop="videoUR">
          <el-input v-model="formData.videoURL"></el-input>
        </el-form-item>
      </el-form>
      <!-- 按钮 -->
      <template v-slot:footer>
        <el-row type="flex" justify="end">
          <el-button plain @click="btnCancel">取消</el-button>
          <el-button type="primary" @click="btnOK">确定</el-button>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { add, detail, update } from '@/api/hmmm/articles'
export default {
  props: {
    showAddDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        title: '',
        articleBody: '',
        videoURL: ''
      },
      rules: {
        title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
        articleBody: [{ required: true, message: '请输入文章内容', trigger: 'blur' }]
      }
    }
  },
  computed: {
    showTitle() {
      return this.formData.id ? '修改文章' : '新增文章'
    }
  },
  methods: {
    btnOK() {
      this.$refs.addForm.validate(async valid => {
        if (valid) {
          if (this.formData.id) {
            await update(this.formData)
            this.$message.success('更新文章成功')
          } else {
            await add(this.formData)
            this.$message.success('添加文章成功')
          }
        }
        // 通知父组件更新视图
        this.$parent.getArticleList()
        this.$emit('update:showAddDialog', false)
      })
    },
    btnCancel() {
      this.$refs.addForm.resetFields()
      this.$emit('update:showAddDialog', false)
    },
    onEditorChange(data) {
      console.log(data)
      // 改变文章内容
      this.formData.articleBody = data.html
    },
    // 编辑文章
    async editArticle(id) {
      const { data } = await detail({ id: id })
      // console.log(data)
      this.formData = data
    }

  }
}
</script>

<style lang='scss' scoped>
::v-deep .ql-container {
  height: 200px;
}
</style>
